package com.example.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.example.common.Result;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.entity.Repair;
import com.example.service.AdminService;
import com.example.service.UserRepairService;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 账单表前端操作接口
 **/
@RestController
@RequestMapping("/user/repair")
public class UserRepairController {

    @Resource
    private UserRepairService userRepairService;

    @Resource
    private AdminService adminService;
    // 文件上传存储路径
    private static final String filePath = System.getProperty("user.dir") + "/files/";
    @Value("${server.port:9090}")
    private String port;
    @Value("${ip:localhost}")
    private String ip;

    /**
     * 新增
     */
    @PostMapping("/add")
    public Result add(@RequestBody Repair repair) {
        repair.setRepairStatus("待处理");
        Account currentUser = TokenUtils.getCurrentUser();
        repair.setUserId(currentUser.getId());
        userRepairService.add(repair);
        // TODO 通知所有管理员
        List<String> toAdmin = new ArrayList<>();
        for(Admin admin : adminService.selectAll(new Admin())){
            toAdmin.add(admin.getUsername());
        }
        userRepairService.notice(toAdmin, "您有新的维修单待分配");
        return Result.success();
    }

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        String flag;
        synchronized (FileController.class) {
            flag = System.currentTimeMillis() + "";
            ThreadUtil.sleep(1L);
        }
        String fileName = file.getOriginalFilename();
        try {
            if (!FileUtil.isDirectory(filePath)) {
                FileUtil.mkdir(filePath);
            }
            // 文件存储形式：时间戳-文件名
            FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName);  // ***/manager/files/1697438073596-avatar.png
            System.out.println(fileName + "--上传成功");

        } catch (Exception e) {
            System.err.println(fileName + "--文件上传失败");
        }
        String http = "http://" + ip + ":" + port + "/files/";
        return Result.success(http + flag + "-" + fileName);  //  http://localhost:9090/files/1697438073596-avatar.png
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id) {
        userRepairService.deleteById(id);
        return Result.success();
    }

    /**
     * 批量删除
     */
    @DeleteMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        userRepairService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public Result updateById(@RequestBody Repair repair) {
        userRepairService.updateById(repair);
        return Result.success();
    }

    /**
     * 评价
     */
    @PostMapping("/evaluate")
    public Result evaluateById(@RequestBody Repair repair) {
        // TODO 添加评价前提判断
        if("已处理".equals(repair.getRepairStatus())){
            userRepairService.evaluateById(repair);
            return Result.success();
        }
        return Result.error(ResultCodeEnum.PROCESS_ERROR);
    }

    /**
     * 根据ID查询
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Repair bill = userRepairService.selectById(id);
        return Result.success(bill);
    }

    /**
     * 查询所有
     */
    @GetMapping("/selectAll")
    public Result selectAll(Repair repair) {
        Account user = TokenUtils.getCurrentUser();
        repair.setUserId(user.getId());
        List<Repair> list = userRepairService.selectAll(repair);
        return Result.success(list);
    }

    /**
     * 分页查询
     */
    @GetMapping("/selectPage")
    public Result selectPage(Repair repair,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        Account user = TokenUtils.getCurrentUser();
        repair.setUserId(user.getId());
        PageInfo<Repair> page = userRepairService.selectPage(repair, pageNum, pageSize);
        return Result.success(page);
    }

    /**
     * 批量导出
     */
    @GetMapping("export")
    public void export(@RequestParam(required = false) Integer userId,  HttpServletResponse response) throws IOException {
    }

    // 统计账单的比例情况
    @GetMapping("/count")
    public Result count(String type) {
        List<Repair> list = userRepairService.count(type);
        return Result.success(list);
    }

}